package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.User;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.LoginServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.LoginService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.JSONObjectUtils;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.UserDataEncryptionUtils;

public class ActivityLogin extends AppCompatActivity {
    //声明变量
    private TextView mregister;
    private ImageView mimageView;
    private EditText muesername, mpassword;
    private Button mconfirm;
    private UserDataEncryptionUtils data;
    private CheckBox checkBox;

    // 登录相关服务类
    private LoginServiceConnection loginConnection;
    // 处理后端传来的JSONObject
    private JSONObjectUtils JSONObjectUtils = new JSONObjectUtils();

    @Override
    protected void onStart() {
        super.onStart();

        loginConnection = new LoginServiceConnection(service -> {});
        Intent intent = new Intent(this, LoginService.class);
        bindService(intent, loginConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (loginConnection.isBound()) {
            unbindService(loginConnection);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //找布局控件对应ID
        mimageView = findViewById(R.id.iv_1);
        muesername = findViewById(R.id.et_username);
        mpassword = findViewById(R.id.et_password);
        mconfirm = findViewById(R.id.btn_confirm);
        mregister = findViewById(R.id.btn_register);
        checkBox=findViewById(R.id.cb_rm);
        data=new UserDataEncryptionUtils(ActivityLogin.this);
        initLogin();

        // 注册按钮的监听事件
        mregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toRegister = new Intent(ActivityLogin.this,ActivityRegister.class) ;
                startActivityForResult(toRegister,1);
            }
        });

        // 登录按钮的监听事件
        mconfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = muesername.getText().toString();
                String password = mpassword.getText().toString();

                User user = new User(username,password);

                JSONObject loginInfo = loginConnection.getService().login(username,password);
                Log.d(username,loginInfo.toString());
                try {
                    Boolean info = loginInfo.getBoolean("success");
                    if(info) {
                        user = JSONObjectUtils.dealLogin(loginInfo,user);
                    }else{
                        Toast.makeText(ActivityLogin.this,"用户名不存在或密码错误",Toast.LENGTH_SHORT).show();
                    }

//                    Log.d("state",user.getRole()+"");
//                    Log.d("username",user.getUsername());
//                    Log.d("password",user.getPassword());
                    //依据身份选择跳转的页面
                    Intent toMain = new Intent(ActivityLogin.this,ActivityProducer.class) ;
                    if (user.getRole() == 1){
                        toMain = new Intent(ActivityLogin.this,ActivityDealer.class) ;
                    }else if (user.getRole() == 2){
                        toMain = new Intent(ActivityLogin.this,ActivityConsumer.class) ;
                    }
                    saveLogin(user);
                    Log.d("user",user.getUserId() + " " + user.getRole() + " " + user.getUsername());
                    startActivity(toMain);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        /*
            requestCode:
            1  ->  ActivityRegister

         */
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Boolean result = Boolean.valueOf(data.getStringExtra("RegisterInfo"));
                if(result) Toast.makeText(ActivityLogin.this,"注册失败",Toast.LENGTH_SHORT).show();
            }
        }
    }



    // 保存登录
    private void saveLogin(User user) {
        SharedPreferences sharedPreferences = getSharedPreferences("ACCOUNT_REMEMBER", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // 存储 User 对象中的数据
        editor.putBoolean("remember", checkBox.isChecked());
        editor.putInt("userId", (user.getUserId() != null) ? user.getUserId() : -1);
        editor.putString("username", (user.getUsername() != null) ? user.getUsername() : "");
        editor.putString("password", (user.getPassword() != null) ? user.getPassword() : "");
        editor.putString("email", (user.getEmail() != null) ? user.getEmail() : "");
        editor.putInt("role", (user.getRole() != null) ? user.getRole() : -1);
        Log.d("验证用户基本信息",user.getUserId() + " " + user.getRole());
        // 提交保存
        editor.apply();
    }


    //初始化登录(用来保存上次登录信息)
    private void initLogin() {
        SharedPreferences sharedPreferences = ActivityLogin.this.getSharedPreferences("ACCOUNT_REMEMBER", MODE_PRIVATE);

        // 获取 JSON 字符串
        String username = sharedPreferences.getString("username", null);
        String password = sharedPreferences.getString("password", null);
        boolean remember = sharedPreferences.getBoolean("remember", false);
        if (remember){
            muesername.setText(username);
            mpassword.setText(password);
        }
        checkBox.setChecked(remember);

    }
}
